package chat

// 连接数据

import (
	"fmt"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

var DB *gorm.DB

func (api *Api) InitDB() {
	// 从yaml文件中加载数据库连接参数

	dbString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", api.Config.Username, api.Config.Password, api.Config.Dbip, api.Config.Mysqlport, api.Config.Dbname)
	var err error
	DB, err = gorm.Open("mysql", dbString)
	if err != nil {
		fmt.Println(err)
		api.Logger.LogError("[错误] 连接失败请检查")
		return // 添加return语句以避免在连接失败时继续执行
	}
	DB.DB().SetMaxOpenConns(100)
	DB.DB().SetMaxIdleConns(10)
	api.LogInfo("[信息] 数据库连接成功")
}

type Users struct {
	ID        uint      `gorm:"primaryKey;autoIncrement"`
	Username  string    `gorm:"type:varchar(50);unique_index"`
	Password  string    `gorm:"type:varchar(125)"`
	CreatedAt time.Time `gorm:"type:datetime;CURRENT_TIMESTAMP"`
	LastLogin time.Time `gorm:"type:datetime;DEFAULT_GENERATED ON UPDATE CURRENT_TIMESTAMP"`
	Money     float32   `gorm:"size:12"`
	Email     string    `gorm:"type:varchar(50);unique_index"`
}

func (api *Api) Example() {
	// Create the table
	DB.AutoMigrate(&Users{})

	// Insert a row
	// user := Users{Username: "test", Password: "123456", CreatedAt: time.Now(), LastLogin: time.Now(), Money: 1000.00, Email: "2109864081@qq.com"}
	// DB.Create(&user)

	// Query the table
	// var result Users
	// DB.First(&result, "id = ?", 2)
	// fmt.Println(result)

	// Update a row
	// DB.Model(&result).Update("username", "longqiang")

	// Delete a row
	// DB.Delete(&result)
}
